'use strict';

angular.module('afasApp')
  .controller('ProvincesCtrl', ['$scope', 'Services', '$state', function ($scope, Services, $state) {

    $scope.provinces = [];
    $scope.countries = [];
    $scope.provinceNew = {};

    function applyRemoteData( newData ) {
      $scope.provinces = newData;
    }

    function loadRemoteData() {
      Services.getItems('provinces')
      .then(function( results ) {
        applyRemoteData( results.data );
      });
    }

    Services.getItems('countries')
    .then(function(results){
      $scope.countries = results.data;
    });

    loadRemoteData();
    // $scope.provinces = Provinces.getProvinces();

    $scope.addProvince = function () {
      Services.add('provinces', $scope.provinceNew)
      .then(function(results){
        console.log(results);
        $scope.provinceNew = {};
        $state.go( 'provinces.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
      // Provinces.addProvince($scope.provinceNew);
    };

    $scope.deleteProvince = function (province) {
      Services.delete('provinces', province)
      .then(function(results){
        console.log(results);
        loadRemoteData();
      });
      // Provinces.deleteProvince(province);
    };
  }]).controller('ProvinceCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.currentProvince = {};
    $scope.currentID = $stateParams.id;
    $scope.countries = [];
    // $scope.currentProvince = Provinces.getProvince($stateParams.id);


    Services.getItems('countries')
    .then(function(results){
      $scope.countries = results.data;
    });

    Services.getItem('provinces', $scope.currentID)
    .then(function(results){
      $scope.currentProvince = results.data;
    });

    $scope.updateProvince = function () {
      $scope.currentProvince.Country = {
        'Id': $scope.currentProvince.Country.Id
      }
      Services.update('provinces', $scope.currentProvince, $scope.currentID)
      .then(function(){
        $state.go( 'provinces.show', {id: $scope.currentID} );
      });
      // Provinces.updateProvince($scope.currentProvince, $scope.currentID);
    };

  }]);
